package com.o2o.controller;

import java.io.IOException;
import java.util.List;

import org.jsoup.Jsoup;
import org.springframework.stereotype.Controller;

import com.o2o.base.BaseControllerAction;
import com.o2o.content.SessionContent;
import com.o2o.factory.CategoryFactory;
import com.o2o.factory.CategorySourceService;
import com.o2o.model.topic.Category;
import com.o2o.model.topic.Topic;
import com.o2o.model.topic.TopicContent;
import com.o2o.model.user.User;
import com.o2o.util.JsoupUtil;

@Controller
public class TopicControllerAction extends BaseControllerAction{

	/**
	 * 
	 */
	private static final long serialVersionUID = 7321551284214344247L;
	
	
	List<Category> allCategoryTree;
	/**
	 *跳转到发主题帖页面 
	 */
	public String sendTopic(){
		allCategoryTree = topicService.getAllCategoryTree(1);
		
		return SUCCESS;
	}
	
	public String queryAllCategory(){
		CategorySourceService categoryFactory = CategoryFactory.getCategoryService();
		List<Category> allCategoryTree =categoryFactory.getAllCategory();
		result.put("content", allCategoryTree);
		result.put("success", true);
		result.put("timestamp", System.currentTimeMillis());
		return SUCCESS;
	}
	
	/**
	 *提交主题帖
	 */
	private String topicTitle;//主题帖title
	private String topicString;//楼主说，主题帖内容
	
	
	private int productType;//商品类型，2为本地生活服务类，1为全新标准商品，3为二手商品
	private int categoryNumber;//商品分类编码
	private String productName;//商品名称
	private float productMarketPrice;//市场价
	private float topicPrice;//活动价格
	private String productPicturePath;//商品图片主图
	
	private String productDescriptionString; //商品detail
	private String productBrand;
	private String productUrl;
	
	public String submitTopic(){
		System.out.println("dsss");
		User user = (User) session.get(SessionContent.NORMAL_USER_SESSION);
		try {
			long topicId = topicService.saveTopicAndProduct(user.getId(),user.getName(), topicTitle, topicString, productName, productMarketPrice, categoryNumber, productPicturePath, productBrand, productType, topicPrice,productUrl, productDescriptionString);
			if(topicId > 0){
				result.put("success", true);
				result.put("redirectUrl", "/topic/topicDetail?tid="+topicId);
				result.put("message", "成功保存主题帖");
			}else{
				result.put("success", false);
				result.put("message", "保存主题帖失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
			result.put("success", false);
			result.put("message", "服务器出现错误");
		}
		result.put("timestamp", System.currentTimeMillis());
		return SUCCESS;
	}
	
	private long tid;
	private Topic topic;
	private List<TopicContent> topicContentList;
	private int hasNextPage = 0;//是否有下一页,然后判断查询结果集合的大小,来认定是否有下一页
	/**
	 *主题帖详细 
	 */
	public String topicDetail(){
			try {
				if(tid > 0){
					topic = topicService.getTopicProductByTopicId(tid);
					topicContentList = topicService.getTopicContentByTopicId(tid, page, pageSize,session);//每次都请求两页的数据
					if(topicContentList != null && topicContentList.size() == pageSize+1){
						//有下一页
						hasNextPage = 1;
						topicContentList = topicContentList.subList(0, topicContentList.size()-1);//去掉测试是否有下一页的那条数据
					}
					return SUCCESS;
				}else return ERROR;
			} catch (Exception e) {
				e.printStackTrace();
				return ERROR;
			}
			
	}
	/**
	 * 查询topic回复
	 */
	private int page = 1;//默认第一页
	private int pageSize = 20;//每页的数量，默认为每页40个
	public String queryTopicContent(){
		pageSize = 20;
		boolean flag = true;
		boolean hasNextPage = false;
		try {
			topicContentList = topicService.getTopicContentByTopicId(tid, page, pageSize,session);
			if(topicContentList != null && topicContentList.size() == pageSize+1){
				hasNextPage = true;//当前page页有下一页
				topicContentList = topicContentList.subList(0, topicContentList.size()-1);//去掉测试是否有下一页的那条数据
				result.put("message", "return result success");
			}
			if(topicContentList == null || topicContentList.size() == 0){
				flag = false;
				result.put("message", "result is empty");
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		result.put("success", flag);
		result.put("result", topicContentList);
		result.put("timestamp", System.currentTimeMillis());
		result.put("hasNextPage", hasNextPage);
		result.put("page", page);
		result.put("pageSize", pageSize);
		return SUCCESS;
	}
	/**
	 *提交主题帖的评论 
	 */
	private long topicUserId;//主题帖用户的id
	private String topicContentString;
	
	private long topicFatherId;//如果为评论回复的内容，则为回复的id
	private long toUserId;
	
	public String submitTopicContent(){
		User user = (User) session.get(SessionContent.NORMAL_USER_SESSION);
		final long now = System.currentTimeMillis();
		try {
			int noticeType = 1;//默认为评论主题帖
			if(topicFatherId > 0){
				//回复的评论
				noticeType = 3;
			}
			if(topicFatherId == 0){
				//编辑器中提交文字，进行处理
				topicContentString = JsoupUtil.parseHtml(topicContentString);
				String parseHtmlNotice = JsoupUtil.parseHtmlToNotice(topicContentString);//处理图片视频音乐为[图片]简单显示形式字符串
			}
			long topicContentId = topicService.saveTopicContent(tid, user.getId(),toUserId, topicContentString, topicFatherId,now);
			if(topicContentId > 0){
				topicService.saveTopicNotice(tid, topicContentString, now, user.getId(), topicUserId,topicContentId,noticeType);
				TopicContent topicContent = topicService.getTopicContentById(topicContentId);
				String contentHtml = topicContent.getContent();
				topicContent.setContent(JsoupUtil.unParseHtml(contentHtml));
				result.put("topicContent", topicContent);
				result.put("success", true);
				result.put("message", "主题帖评论成功");
			}else{
				result.put("success", false);
				result.put("message", "主题帖评论保存数据库失败");
			}
		} catch (Exception e) {
			logger.error(e.toString());
			result.put("success", false);
			result.put("message", "主题帖评论保存失败error");
		}
		result.put("timestamp", System.currentTimeMillis());
		return SUCCESS;
		
	}
	private int cid;	//categorynumber
	/**
	 * 社区购物商品列表
	 */
	private int type;//类型，1，社区购物，2本地生活服务,3二手
	private List<Category> cates;
	private List<Topic> topicList;
	
	private List<Category> firstCates;
	private List<Category> secondCates;
	private List<Category> thirdCates;
	private Category firstCate;
	private Category secondCate;
	private Category thirdCate;//默认0为选中全部
	private int sort = 1;//sort 排序方式:1,以主题帖的热度,2发布时间倒序,///未实现3销量,4评分,5价格,默认为热度倒序
	private String q = "";
	public String topicShopList(){
		type = 1;
		pageSize = 10;
		int level = 0;
		try {
			if(cid == 0){//默认第一个分类选中
				cid = 1000000;
			}
			CategorySourceService categoryFactory = CategoryFactory.getCategoryService();
			
			Category category = categoryFactory.getCategory(cid);
			if(category != null){
				level = category.getLevel();
				if(level >= 1){
					firstCates = categoryFactory.getFirstCategorys(type);
				}
				if(level >= 2){
					firstCate = categoryFactory.getSecondCategoryByNumber(cid, 1);
					secondCates =categoryFactory.getCategoryListByPid(firstCate.getId());
				}
				if(level >= 3){
					secondCate = categoryFactory.getThirdCategoryByNumber(cid, 1);
					thirdCates  = categoryFactory.getCategoryListByPid(secondCate.getId());
				}
				if(level == 4){
					thirdCate = category;
				}
			}
			if(q != null && !"".equals(q)){
				//使用sphinx搜索
				topicList = topicService.getTopicListBySphinxSearch(q,cid, type,sort, page, pageSize);
			}else{
//				数据库直接查找
				topicList = topicService.getTopicListByCategoryNumber(cid, type,sort, page, pageSize,session);
			}
			if(topicList != null && topicList.size() == pageSize+1){
				hasNextPage = 1;//当前page页有下一页
				topicList = topicList.subList(0, topicList.size()-1);//去掉测试是否有下一页的那条数据
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return SUCCESS;
	}
	/**
	 * 异步获取主题帖列表
	 * @return
	 */
	public String ajaxTopicList(){
		pageSize = 10;
		boolean flag = true;
		boolean hasNextPage = false;
		try {
			if(q != null && !"".equals(q)){
				//使用sphinx搜索
				topicList = topicService.getTopicListBySphinxSearch(q,cid, type,sort, page, pageSize);
			}else{
//				数据库直接查找
				topicList = topicService.getTopicListByCategoryNumber(cid, type,sort, page, pageSize,session);
			}
			if(topicList != null && topicList.size() == pageSize+1){
				hasNextPage = true;//当前page页有下一页
				topicList = topicList.subList(0, topicList.size()-1);//去掉测试是否有下一页的那条数据
				result.put("message", "return result success");
			}
			if(topicList == null || topicList.size() == 0){
				flag = false;
				result.put("message", "result is empty");
			}
		} catch (Exception e) {
			flag = false;
			result.put("message", e.getMessage());
			e.printStackTrace();
		}
		result.put("success", flag);
		result.put("result", topicList);
		result.put("timestamp", System.currentTimeMillis());
		result.put("hasNextPage", hasNextPage);
		result.put("page", page);
		result.put("pageSize", pageSize);
		return SUCCESS;
	}
	
	public void setTopicUserId(long topicUserId) {
		this.topicUserId = topicUserId;
	}

	/**
	 * 本地生活服务topic列表
	 */
	public String topicServiceList(){
		type = 2;
		pageSize = 10;
		int level = 0;
		try {
			if(cid == 0){//默认第一个分类选中
				cid = 2010000;
			}
			CategorySourceService categoryFactory = CategoryFactory.getCategoryService();
			
			Category category = categoryFactory.getCategory(cid);
			if(category != null){
				level = category.getLevel();
				if(level >= 1){
					firstCates = categoryFactory.getFirstCategorys(type);
				}
				if(level >= 2){
					firstCate = categoryFactory.getSecondCategoryByNumber(cid, 1);
					secondCates =categoryFactory.getCategoryListByPid(firstCate.getId());
				}
				if(level >= 3){
					secondCate = categoryFactory.getThirdCategoryByNumber(cid, 1);
					thirdCates  = categoryFactory.getCategoryListByPid(secondCate.getId());
				}
				if(level == 4){
					thirdCate = category;
				}
			}
//			topicList = topicService.getTopicListByCategoryNumber(cid, type, page, pageSize, sort,session);
			if(q != null && !"".equals(q)){
				//使用sphinx搜索
				topicList = topicService.getTopicListBySphinxSearch(q,cid, type,sort, page, pageSize);
			}else{
//				数据库直接查找
				topicList = topicService.getTopicListByCategoryNumber(cid, type,sort, page, pageSize,session);
			}
			if(topicList != null && topicList.size() == pageSize+1){
				hasNextPage = 1;//当前page页有下一页
				topicList = topicList.subList(0, topicList.size()-1);//去掉测试是否有下一页的那条数据
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
		return SUCCESS;
	}
	/**
	 * 二手topic
	 */
	public String topicOldList(){
		type = 3;
		pageSize = 10;
		int level = 0;
		try {
			if(cid == 0){//使用标准商品分类
				cid = 1000000;
			}
			CategorySourceService categoryFactory = CategoryFactory.getCategoryService();
			
			Category category = categoryFactory.getCategory(cid);//点击的当前分类
			if(category != null){
				level = category.getLevel();
				if(level >= 1){
					firstCates = categoryFactory.getFirstCategorys(type);
				}
				if(level >= 2){
					firstCate = categoryFactory.getSecondCategoryByNumber(cid, 1);
					secondCates =categoryFactory.getCategoryListByPid(firstCate.getId());
				}
				if(level >= 3){
					secondCate = categoryFactory.getThirdCategoryByNumber(cid, 1);
					thirdCates  = categoryFactory.getCategoryListByPid(secondCate.getId());
				}
				if(level == 4){
					thirdCate = category;
				}
			}
		if(q != null && !"".equals(q)){
			//使用sphinx搜索
			topicList = topicService.getTopicListBySphinxSearch(q,cid, type,sort, page, pageSize);
		}else{
//			数据库直接查找
			topicList = topicService.getTopicListByCategoryNumber(cid, type,sort, page, pageSize,session);
		}
			if(topicList != null && topicList.size() == pageSize+1){
				hasNextPage = 1;//当前page页有下一页
				topicList = topicList.subList(0, topicList.size()-1);//去掉测试是否有下一页的那条数据
			}
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR;
		}
		return SUCCESS;
	}
	/**
	 * 异步赞或者取消赞主题帖
	 */
	public String ajaxTopicGreat(){
		int saveTopicGreat = 0;
		boolean flag = true;
		try {
			User user = (User) session.get(SessionContent.NORMAL_USER_SESSION);
			saveTopicGreat = topicService.saveTopicGreat(tid, user.getId());
			if(saveTopicGreat == 1){
				result.put("message", "赞主题帖成功");
			}
			if(saveTopicGreat == 2){
				result.put("message", "已经赞");
			}
			if(saveTopicGreat == 0){
				result.put("message", "操作失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
			flag = false;
		}
		result.put("topicId", tid);
		result.put("code", saveTopicGreat);
		result.put("success", flag);
		result.put("timestamp", System.currentTimeMillis());
		return SUCCESS;
	}
	
	/**
	 * 异步赞或者取消赞主题帖
	 */
	private long contentId;
	public String ajaxContentGreat(){
		int saveContentGreat = 0;
		boolean flag = true;
		try {
			User user = (User) session.get(SessionContent.NORMAL_USER_SESSION);
			saveContentGreat = topicService.saveContentGreat(contentId, user.getId());
			if(saveContentGreat == 1){
				result.put("message", "赞回复成功");
			}
			if(saveContentGreat == 2){
				result.put("message", "已经赞");
			}
			if(saveContentGreat == 0){
				result.put("message", "操作失败");
			}
		} catch (Exception e) {
			e.printStackTrace();
			flag = false;
		}
		result.put("contentId", contentId);
		result.put("code", saveContentGreat);
		result.put("success", flag);
		result.put("timestamp", System.currentTimeMillis());
		return SUCCESS;
	}

	

	public void setTopicPrice(float topicPrice) {
		this.topicPrice = topicPrice;
	}

	public void setContentId(long contentId) {
		this.contentId = contentId;
	}

	public void setToUserId(long toUserId) {
		this.toUserId = toUserId;
	}

	public String getQ() {
		return q;
	}

	public void setQ(String q) {
		this.q = q;
	}

	public int getCid() {
		return cid;
	}

	public void setCid(int cid) {
		this.cid = cid;
	}

	public int getType() {
		return type;
	}


	public int getSort() {
		return sort;
	}

	public void setSort(int sort) {
		this.sort = sort;
	}

	public void setType(int type) {
		this.type = type;
	}

	public int getCategoryNumber() {
		return categoryNumber;
	}

	public List<Category> getCates() {
		return cates;
	}

	public List<Topic> getTopicList() {
		return topicList;
	}

	public void setTopicFatherId(long topicFatherId) {
		this.topicFatherId = topicFatherId;
	}

	public List<Category> getFirstCates() {
		return firstCates;
	}

	public List<Category> getSecondCates() {
		return secondCates;
	}

	public List<Category> getThirdCates() {
		return thirdCates;
	}

	public Category getFirstCate() {
		return firstCate;
	}

	public Category getSecondCate() {
		return secondCate;
	}

	public Category getThirdCate() {
		return thirdCate;
	}

	public void setTopicContentString(String topicContentString) {
		this.topicContentString = topicContentString;
	}

	public int getHasNextPage() {
		return hasNextPage;
	}

	public List<TopicContent> getTopicContentList() {
		return topicContentList;
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public int getPageSize() {
		return pageSize;
	}

	public void setPageSize(int pageSize) {
		this.pageSize = pageSize;
	}



	public Topic getTopic() {
		return topic;
	}

	public void setTopic(Topic topic) {
		this.topic = topic;
	}

	public void setTid(long tid) {
		this.tid = tid;
	}
	

	public long getTid() {
		return tid;
	}

	public void setTopicTitle(String topicTitle) {
		this.topicTitle = topicTitle;
	}

	

	public void setTopicString(String topicString) {
		this.topicString = topicString;
	}

	public void setProductType(int productType) {
		this.productType = productType;
	}

	public void setCategoryNumber(int categoryNumber) {
		this.categoryNumber = categoryNumber;
	}

	public void setProductName(String productName) {
		this.productName = productName;
	}

	public void setProductMarketPrice(float productMarketPrice) {
		this.productMarketPrice = productMarketPrice;
	}


	public void setProductPicturePath(String productPicturePath) {
		this.productPicturePath = productPicturePath;
	}

	

	public void setProductDescriptionString(String productDescriptionString) {
		this.productDescriptionString = productDescriptionString;
	}

	public List<Category> getAllCategoryTree() {
		return allCategoryTree;
	}

	public void setProductBrand(String productBrand) {
		this.productBrand = productBrand;
	}

	
	

}
